package com.neusoft.elm.view.impl;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.neusoft.elm.dao.BusinessDao;
import com.neusoft.elm.dao.impl.BusinessDaoImpl;
import com.neusoft.elm.po.Business;
import com.neusoft.elm.view.BusinessView;

public class BusinessViewImpl implements BusinessView{
	
	private Scanner input = new Scanner(System.in);
	
	@Override
	  public void countBusiness(){
	      BusinessDao dao = new BusinessDaoImpl();
	      int count = dao.countBusiness();
	      System.out.println("商家数量：" + count);
	  }
	
	
	@Override
	public void listBusinessAll() {
		BusinessDao dao = new BusinessDaoImpl();
		List<Business> list = dao.listBusiness(null,null);
		
		 System.out.printf("%-8s\t%-40s\t%-60s\t%-4s\t%-6s\t%-6s\n",
		            "商家编号", "商家名称", "商家地址", "商家介绍", "起送费", "配送费");
		    
		 for (Business b : list) {
			    Integer businessId = b.getBusinessId();
			    String businessName = b.getBusinessName();
			    String businessAddress = b.getBusinessAddress();
			    String businessExplain = b.getBusinessExplain();
			    double starPrice = b.getStarPrice();
			    double deliveryPrice = b.getDeliveryPrice();

			    System.out.printf("%-4s\t%-26s\t%-36s\t%-8s\t%-4.2f\t%-6.2f\n",
			            (businessId + "    ").substring(0, 5),
			            (businessName + "                          ").substring(0, 26),
			            (businessAddress + "                                    ").substring(0, 36),
			            (businessExplain + "        ").substring(0, 8),
			            starPrice,
			            deliveryPrice);
			}
	}
	
	  @Override
	  public void listBusiness() {
		  String businessName= "";
		  String businessAddress= "";
		  	  
		  String inputStr = "";
		  System.out.println("是否需要输入商家名称关键词（y/n）");
		  inputStr = input.next();
		  if(inputStr.equals("y")) {
			  System.out.println("请输入商家名称关键词");
			  businessName = input.next();
	      }
		  
		  
		  System.out.println("是否需要输入商家地址关键词（y/n）");
		  inputStr = input.next();
		  if(inputStr.equals("y")) {
			  System.out.println("请输入商家地址关键词:");
			  businessAddress = input.next();
	      }
		  
		  BusinessDao dao = new BusinessDaoImpl();
		  List<Business> list = dao.listBusiness(businessName,businessAddress);
		  System.out.printf("%-8s\t%-40s\t%-60s\t%-4s\t%-6s\t%-6s\n",
		            "商家编号", "商家名称", "商家地址", "商家介绍", "起送费", "配送费");
		    
		    for (Business b : list) {
		        System.out.printf("%-4s\t%-26s\t%-36s\t%-8s\t%-4.2f\t%-6.2f\n",
		                b.getBusinessId(), b.getBusinessName(), b.getBusinessAddress(),
		                b.getBusinessExplain(), b.getStarPrice(), b.getDeliveryPrice());
		    }
	      }
	  
	  
	  @Override
	  public void addBusiness() {
	      System.out.println("请输入新建商家名称，多个商家名称使用逗号分隔:");
	      String inputNames = input.nextLine();
	      List<String> businessNames = Arrays.asList(inputNames.split("，"));
	      if (businessNames.isEmpty()) { 
	          System.out.println("商家名称不能为空！");
	          return;  
	      }
	      BusinessDao dao = new BusinessDaoImpl();
	      int[] result = dao.addBusiness(businessNames);

	      for (int i = 0; i < businessNames.size(); i++) {
	          if (result[i] > 0) {
	              System.out.println("商家 '" + businessNames.get(i) + "' 插入成功！");
	          } else {
	              System.out.println("商家 '" + businessNames.get(i) + "' 插入失败！");
	          }
	      }
	  }
	  
	  @Override
	  public void removeBusiness() {
	      System.out.println("请输入要删除的商家编号，多个商家编号使用逗号分隔:");
	      String inputIds = input.nextLine();
	      List<Integer> businessIds;
	      try {
	          businessIds = Arrays.stream(inputIds.split("，"))
	                  .map(Integer::parseInt)
	                  .collect(Collectors.toList());
	      } catch (NumberFormatException e) {
	          System.out.println("输入的商家编号格式不正确！");
	          return;
	      }
	      
	      businessIds.sort(Comparator.reverseOrder());
	      BusinessDao dao = new BusinessDaoImpl();

	      int totalDeleted = 0;
	      for (Integer businessId : businessIds) {
	          try{
	              int result = dao.removeBusiness(Arrays.asList(businessId));
	              if (result > 0) {
	                  System.out.println("商家编号 " + businessId + " 删除成功！");
	                  totalDeleted += result; 
	              } else {
	                  System.out.println("商家编号 " + businessId + " 删除失败！");
	              }
	          } catch (Exception e){
	              System.out.println("商家编号 " + businessId + " 删除失败！出现异常：" + e.getMessage());
	          }
	      }
	      System.out.println("共删除 " + totalDeleted + " 个商家。");
	  }
	  
	  @Override
	  public Business login(){
		    System.out.println("请输入商家编号：");
		    int businessId = 0;
		    
		    while (true) {
		        if (input.hasNextInt()) {
		            businessId = input.nextInt();
		            break;
		        } else {
		            System.out.println("商家编号无效，请重新输入数字商家编号：");
		            input.next(); 
		        }
		    }
			System.out.println("请输入密码：");
			String password = input.next();
			
			BusinessDao dao = new BusinessDaoImpl();
			return dao.getBusinessByIdByPass(businessId, password);
	  }
	  
	  @Override
	  public void showBusiness(Integer businessId) {
		  BusinessDao dao = new BusinessDaoImpl();
		  Business business =dao.getBusinessById(businessId);
		  System.out.println(business);
	  }
	  
	  
	  @Override
	  public void editBusiness(Integer businessId) {
	      BusinessDao dao = new BusinessDaoImpl();
	      Business business = dao.getBusinessById(businessId);
	      System.out.println(business);

	      Scanner input = new Scanner(System.in);
	      String inputStr;
	      
	      Business originalBusiness = new Business();
	      originalBusiness.setBusinessName(business.getBusinessName());
	      originalBusiness.setBusinessAddress(business.getBusinessAddress());
	      originalBusiness.setBusinessExplain(business.getBusinessExplain());
	      originalBusiness.setStarPrice(business.getStarPrice());
	      originalBusiness.setDeliveryPrice(business.getDeliveryPrice());
	      originalBusiness.setDeliveryDistance(business.getDeliveryDistance());
	      
	      while (true) {
	    	  System.out.print("请选择要修改的商家信息（1-商家名称，2-商家地址，3-商家介绍，4-起送费，5-配送费，6-配送距离，7-完成修改）：");
		      System.out.println("\n请选择要更新的食品信息：");
	          System.out.println("1. 商家名称");
	          System.out.println("2. 商家地址");
	          System.out.println("3. 商家介绍");
	          System.out.println("4. 起送费");
	          System.out.println("5. 配送费");
	          System.out.println("6. 配送距离");
	          System.out.println("7. 完成修改");
	    	  
	    	  int option = input.nextInt();
	    	  
	    	  
	    	  switch (option) {
	          	case 1:
	          		System.out.print("请输入新的商家名称：");
	          		business.setBusinessName(input.next());
	          		break;
	          	case 2:
	          		System.out.print("请输入新的商家地址：");
	          		business.setBusinessAddress(input.next());
	          		break;
	          	case 3:
	          		System.out.print("请输入新的商家介绍：");
	          		business.setBusinessExplain(input.next());
	          		break;
	          	case 4:
	          		while (true) {
	          			System.out.print("请输入新的起送费：");
	          			if (input.hasNextDouble()) {
	          				business.setStarPrice(input.nextDouble());
	          				break;
	          			} else {
	          				System.out.println("起送费无效，请重新输入数字起送费：");
	          				input.next();
	          			}
	          		}
	          		break;
	          	case 5:
	          		while (true) {
	          			System.out.print("请输入新的配送费：");
	          			if (input.hasNextDouble()) {
	          				business.setDeliveryPrice(input.nextDouble());
	          				break;
	          			} else {
	          				System.out.println("配送费无效，请重新输入配送费：");
	          				input.next();
	          			}
	          		}
	          		break;
	          	case 6:
	          		System.out.print("请输入新的商家距离：");
	          		business.setDeliveryDistance(input.next());
	          		break;
	          	case 7:
	          		 if (business.BusinessEquals(originalBusiness)) {
	                     System.out.println("没有进行任何修改！");
	                     return;
	                 }

	                 int result = dao.updateBusiness(business);
	                 if (result > 0) {
	                     System.out.println("商家信息修改成功！");
	                 } else {
	                     System.out.println("商家信息修改失败！");
	                 }
	                 return;
	          	default:
	          		System.out.println("无效的选项！");
	          		break;
	    	  }
	      }
	  }


	  
	  @Override
	  public void updateBusinessPassword(Integer businessId) {
		  BusinessDao dao = new BusinessDaoImpl();
		  Business business =dao.getBusinessById(businessId);
		  
		  Scanner scanner = new Scanner(System.in);
		  
		  System.out.print("\n请输入旧密码：");
		  String oldPass = scanner.nextLine();
		  
		  System.out.println("请输入新密码（密码规则：8~20位，包含大小写字母、数字、特殊字符（!@#$%^&*()_+））：");
		  String newpassword = scanner.nextLine();
		  System.out.print("\n请再次输入新密码：");
		  String confirmPassword = scanner.nextLine();
		  
		  Pattern pattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*()_+])[a-zA-Z\\d!@#$%^&*()_+]{8,20}$");
		  
		  if(!business.getPassword().equals(oldPass)) {
			  System.out.print("\n旧密码输入错误！");
		  }else if(!newpassword.equals(confirmPassword)) {
			  System.out.print("\n两次输入密码不一致！");
		  }else if (!pattern.matcher(newpassword).matches()) {
		        System.out.println("新密码不符合规则，请重新输入。");
		        return;
		  }
		  else {
			  int result = dao.updateBusinessPassword(businessId, newpassword);
			  if(result>0) {
				  System.out.print("\n密码修改成功！");
			  }else {
				  System.out.print("\n密码修改失败！请尝试");
			  }
		  }
	  }
	  
	  
  }
